<template>
  <div>
    <!--面包屑导航栏-->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <router-link to="/home/goods">商品管理</router-link>
      </el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!--卡片区域-->
    <el-card>
      <!--警告区域-->
      <el-alert
          title="添加商品信息"
          type="info"
          center
          show-icon
          :closable="false">
      </el-alert>
      <!--进度条区域-->
      <el-steps :active="activeIndex-0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!--垂直排列的标签页-->
      <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="100px" label-position="top">
        <el-tabs tab-position="left" v-model="activeIndex" :before-leave="onClick" @tab-click="onTab">
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                  v-model="addForm.goods_cat"
                  :options="cateList"
                  :props="{ expandTrigger: 'hover',label:'cat_name',children:'children',value:'cat_id'}"
                  @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <!--渲染表单的item项-->
            <el-form-item :label="item.attr_name" v-for="item in manyTableList" :key="item.attr_id">
              <!--复选框组-->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox border :label="cb" v-for="(cb,i) in item.attr_vals" :key="i"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableList" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <!--action 属性表示图片要上传到的后台的api地址 -->
            <el-upload
                action="https://lianghj.top:8888/api/private/v1/upload"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :headers="headersObj"
                list-type="picture"
                :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <!--这里是富文本编辑器区域-->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!--这里是添加商品按钮它会将整个addFrom里的数据通过axios发送个后台-->
            <el-button type="primary" class="bthAdd" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!--这里是图片预览的对话框-->
    <el-dialog
        title="图片预览"
        :visible.sync="dialogVisible"
        width="50%">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
import login from "@/components/Login";

export default {
  name: "Add",
  data() {
    return {
      //这个用来控制步骤条的被激活的项
      activeIndex: '0',
      //添加商品的表单数据对象
      addForm:
          {
            goods_name: '',
            goods_price: 0,
            goods_weight: 0,
            goods_number: 0,
            //商品分类id数组
            goods_cat: [],
            //表示上传的图片路径的数组
            pics: [],
            //这里是与富文本编辑器实现了双向绑定的数据
            goods_introduce: '',
            //这里是存储静态和动态参数的数组
            attrs: []


          },
      //表的的验证规则对象
      addFormRules:
          {
            goods_name: [
              {required: true, message: '请输入商品名称', trigger: 'blur'},
            ],
            goods_price: [
              {required: true, message: '请输入商品价格', trigger: 'blur'},
            ],
            goods_weight: [
              {required: true, message: '请输入商品重量', trigger: 'blur'},
            ],
            goods_number: [
              {required: true, message: '请输入商品数量', trigger: 'blur'},
            ],
            goods_cat: [
              {required: true, message: '请输入商品分类', trigger: 'blur'}
            ]

          },
      //商品分类数据
      cateList: [],
      //动态参数数据列表
      manyTableList: [],
      //商品属性数据列表
      onlyTableList: [],
      //图片上传请求头
      headersObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      //这个是控制图片预览对话框的显示和隐藏
      dialogVisible: false,
      //这里预览时的图片路径
      imgSrc: ''

    }
  },
  methods:
      {
        async getCateList() {
          const {data: res} = await this.$http.get('categories');
          if (res.meta.status !== 200) return this.$message.error("获取商品分类数据失败")
          this.cateList = res.data;
          console.log(this.cateList)
        },
        //级联选择器选中项变化
        handleChange() {
          if (this.addForm.goods_cat.length !== 3) {
            this.addForm.goods_cat = []
          }
        },
        //当标签页进行切换时触发
        onClick(newIndex, oldIndex) {
          if (this.addForm.goods_cat.length !== 3 && (oldIndex - 0) === 0) {
            this.$message.error("请先填写商品分类信息")
            return false;
          }
          return true;
        },
        //点击标签页时触发
        async onTab() {
          //这里是表示你点击的是商品参数这个标签页
          if (this.activeIndex === '1') {
            const {data: res} = await this.$http.get(`categories/${this.goodsId}/attributes`, {params: {sel: 'many'}})
            if (res.meta.status !== 200) return this.$message.error("获取商品参数信息失败");
            this.manyTableList = res.data;
            res.data.forEach((item) => {
              item.attr_vals = item.attr_vals.length === 0 ? [] : item.attr_vals.split(",")
            })
          }
          //这里是表示你点击的是商品属性这个标签页
          if (this.activeIndex === '2') {
            const {data: res} = await this.$http.get(`categories/${this.goodsId}/attributes`, {params: {sel: 'only'}})
            if (res.meta.status !== 200) return this.$message.error('获取商品属性信息失败');
            this.onlyTableList = res.data

          }
        },
        //图片预览的回调函数
        handlePreview(fil) {
          console.log(fil.response.data.url)
          this.imgSrc = fil.response.data.url
          this.dialogVisible = true;
        },
        //点击删除按钮的回调
        handleRemove(fil) {
          const filter = fil.response.data.tmp_path;
          const i = this.addForm.pics.findIndex(x => {
            x.pic === filter;
          })
          this.addForm.pics.splice(i, 1);
          console.log(this.addForm.pics)
        },
        //监听图片上传成功的事件
        handleSuccess(dataObj, fil, filList) {
          console.log(dataObj)
          console.log(fil)
          console.log(filList)
          const picInfo = {
            pic: dataObj.data.tmp_path
          }
          this.addForm.pics.push(picInfo);
        },
        //点击添加商品按钮后的回调函数
        async add() {
          await this.$refs.addForm.validate(async valid => {
            if (!valid) return this.$message.error("你的表单信息未填写完整请重新填写")
            //这里是进行深拷贝防止一些因为数据类型变化参数的报错
            const form = _.cloneDeep(this.addForm)
            form.goods_cat = form.goods_cat.join(',')

            this.manyTableList.forEach(item => {
              const newInfo = {
                attr_id: item.attr_id,
                attr_value: item.attr_vals.join(' ')
              }
              this.addForm.attrs.push(newInfo)
            })

            this.onlyTableList.forEach(item => {
              const newInfo = {
                attr_id: item.attr_id,
                attr_value: item.attr_vals
              }
              this.addForm.attrs.push(newInfo)
            })
            form.attrs = this.addForm.attrs
            const {data: res} = await this.$http.post('goods', form)
            if (res.meta.status !== 201) return this.$message.error("添加商品失败")
            this.$message.success("添加商品成功")
            await this.$router.push('/home/goods')
          })
        }
      },
  computed: {
    //这个计算属性代币商品的三级分类id
    goodsId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  },
  created() {
    this.getCateList();
  }
}
</script>

<style scoped lang="less">
.bthAdd {
  margin-top: 15px;
}

</style>
